var express = require('express');
const studentModels = require('../models/studentModels.js');
var router = express.Router();
const userModels=require('../models/userModels.js')
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('login',);
});
//登录页面
router.get('/login', function(req, res, next) {
  res.render('login');
});
//验证登录页面
router.post('/login', function(req, res, next) {
  let username=req.body.username
  let posswrod=req.body.posswrod
  userModels.findOne({username:req.body.username}).then((data)=>{
	  if(data.posswrod===posswrod){
		  res.cookie('name','zhangsan')
		  studentModels.find().then((data)=>{
		  	res.render('students',{
		  		students:data,
		  		title:req.body.name
		  	})
		  })
	  }else{
		  console.log(data,posswrod)
		  res.send("密码错误")
		  }
  }).catch(err=>{
	  res.status(500).send("密码错误")
  })

});
//注册页面
router.get('/sign', function(req, res, next) {
  res.render('sign');
});
router.post('/sign', function(req, res, next) {
	userModels.create({
		...req.body
	}).then((data)=>{
		res.redirect('login')
	}).catch(err=>{
		res.status(500).send('插入失败')
		return
	})
});
//中间件
let zjj=function(req,res,next){
	if(!cookie.name){
		res.redirect('login')
	}
	next()
}
//学生页面
router.get('/students',function(req,res,next){
	studentModels.find().then((data)=>{
		console.log(data)
		res.render('students',{
			students:data,
			title:req.body.name
		})
	}).catch(err=>{
		res.status(500).send('插入失败')
		return
	})
})
router.post('/students',function(req,res,next){
	res.cookie('name','zhangsan')
	studentModels.create({
		...req.body
	}).then((data)=>{
		res.redirect('students')
	}).catch(err=>{
		res.status(500).send('插入失败')
		return
	})
})
//新生报到
router.get('/student', function(req, res, next) {
  res.render('student');
});
module.exports = router;
